'''
Gets all the parts for a given Dell service tag, to create a new Self-Dispatch
Support Request.
'''
import PySimpleGUI as sg
from warranty_manager.gui.confirmation import get_confirmation
from warranty_manager.claim.dell.common import get_access_token
from warranty_manager.claim.dell.dispatch_api import (
    get_parts_by_service_tag, get_parts_by_device_type,
)
from warranty_manager.claim.dell.handlers import validate_part_finder
from warranty_manager.claim.dell.part_finder_layout import layout


window = sg.Window('Dell Part Finder', layout)

while True:
    event, values = window.read()

    if event in (None, 'Cancel'):
        break
    elif event == 'Get Parts by Service Tag':
        try:
            username, password, tag, sandbox \
            = validate_part_finder(values, is_tag=True)
        except TypeError:
            continue

        if get_confirmation("create a file with this service tag's part numbers"):
            token = get_access_token('Dispatch', sandbox=sandbox)

            if token:
                get_parts_by_service_tag(
                    username, password, token, tag, sandbox=sandbox
                )

    elif event == 'Get Parts by Device Type':
        try:
            username, password, device_type, sandbox \
            = validate_part_finder(values, is_type=True)
        except TypeError:
            continue

        if get_confirmation("create a file with this device type's part numbers"):
            token = get_access_token('Dispatch', sandbox=sandbox)

            if token:
                get_parts_by_device_type(
                    username, password, token, device_type, sandbox=sandbox
                )

    else:
        continue

window.close()
